Gikam.extend(Gikam, {

    rightClickEvent : function(selections){
        Gikam.getComp('lims-square-hole-detail-form').setData(selections[0]);
        let model = Gikam.create('modal', {
            title: 'GIKAM.BUTTON.EDIT',
            width : 200,
            height : 250,
        });
        Gikam.create('layout', {
            renderTo: model.window.$dom,
            center: {
                items: [{
                    type: 'form',
                    id: 'lims-global-board-hole-form',
                    columns : 1,
                    titleWidth : 110,
                    fields : limsLocationBoard.getBoardHoleParamFields(),
                    autoSave: false
                }, {
                    type: 'btnToolbar',
                    items: [{
                        type: 'button',
                        text: 'GIKAM.BUTTON.CONFIRM',
                        icon: 'save',
                        onClick: function () {
                            let form = Gikam.getComp('lims-global-board-hole-form');
                            if (form.validate()) {
                                let data = form.getData();
                                Gikam.postText(limsLocationBoard.baseUrl + '/right/click', Gikam.getJsonWrapper(null, [null, selections],[null,[data]])).done(function () {
                                    Gikam.getComp('lims-location-square-board-edit-list-grid').refreshRowById(selections[0].boardId);
                                    Gikam.refreshHole(selections[0].boardId);
                                });
                                Gikam.getLastModal().close(data);
                            }
                        }
                    }, {
                        type: 'button',
                        text: 'GIKAM.BUTTON.BACK',
                        icon: 'back',
                        onClick: function () {
                            Gikam.getLastModal().close();
                        }
                    }]
                }]
            }
        })
    },

    refreshHole : function(id){
        Gikam.postSync(limsLocationBoard.holeUrl + '/queries', Gikam.getJsonWrapper({
            f: {
                boardId_EQ: id
            },
            o: [{
                y : 'asc'
            },{
                x : 'asc'
            }],
            n: -1, s: -1
        })).done(function (data) {
            const  iframDom=document.querySelector("#ksh-location-square-board-iframe >iframe");
            let flag=false;  //是否初次加载
            iframDom.onload=function(){
                flag =true;
                iframDom.contentWindow.postMessage(data.rows, "*");
            };
            if(!flag){
                iframDom.contentWindow.postMessage(data.rows, "*");
            }
        });
    },

    setHoleItem : function(data){
        if (Gikam.isNotEmpty(data)){
            Gikam.getComp('lims-square-hole-detail-form').setData(data);
        }
    },

    getFormatterGridColumns: function (columns, isAddType) {
        let index = 5;
        if (isAddType === 'true') {
            index = index + 1;
        }
        columns.splice(index, 0, {
            field: 'operation',
            title: 'T_LIMS_REPORT_TEMPLATE.OPTION',
            contentAlign: 'center',
            width: 300,
            sort: false,
            formatter: function (index, value, row) {
                return Gikam.printf('<a href="javascript:;" onclick="Gikam.openFile(\'{id}\', false)">{name}</a>&nbsp;&nbsp;<a href="javascript:;" onclick="downloadFile(\'{url}\',\'{fileName}\',\'{id4}\', true)">{download}</a>&nbsp;&nbsp;<a href="javascript:;" onClick="createFileOperationLogModal(\'{id2}\', true)">{option}</a>', {
                    id: row.id,
                    name: Gikam.propI18N('T_CORE_FILE.OPERATE.PREVIEW'),
                    url: IFM_CONTEXT + row.downloadUrl,
                    fileName: row.name,
                    id4: row.id,
                    download: Gikam.propI18N('T_CORE_FILE.OPERATE.DOWNLOAD'),
                    id2: row.id,
                    option: Gikam.propI18N('T_CORE_FILE.OPERATE.OPERATION.RECORD')
                });
            }
        });
        return columns.slice(0, index + 1);
    },

    // 报告模板管理-下载
    reportTemplateDownload : function (fileId) {
        if (Gikam.isEmpty(fileId)){
            Gikam.alert('CORE.MODULE.EQUIPT.FILEACQCONFIGS.TIP.UPLOAD_FILE');
            return;
        }
        Gikam.getJson(Gikam.IFM_CONTEXT + '/core/module/item/files/' + fileId).done(function (file) {
            Gikam.download(file.downloadUrl);
        });
    },

    createLimsModal: function (e) {
        var t = Gikam.create("modal", {title: e.title, width: e.width, height: e.height}),
            a = [],
            n = {
                type: "btnToolbar",
                items: [{
                    type: "button",
                    text: "GIKAM.BUTTON.CONFIRM",
                    class: "blue",
                    icon: 'save',
                    color: 'white',
                    hidden: e.hideButton,
                    onClick: function () {
                        e.onConfirm()
                    }
                },{
                    type: "button",
                    text: "GIKAM.BUTTON.CANCEL",
                    icon: 'back',
                    hidden: e.hideButton,
                    onClick: function () {
                        Gikam.getLastModal().close();
                    }
                },]
            };
        if(Gikam.isNotEmpty(e.m)){
            a.push(e.m);
        }
        if(Gikam.isNotEmpty(e.b)){
            a.push(e.b);
        } else {
            a.push(n);
        }
        var i = Gikam.create("layout",
            {
                renderTo: t.window.$dom,
                center: {items: a}
            });

        return {modal: t, layout: i}
    },

    preInsert: function(options) {
        const def = Gikam.jQuery.Deferred();

        //分区域展示的字段
        if (options.fields && this.isNotEmpty(options.fields) && this.isNotEmpty(options.fields[0].fields)) {
            options.fields = options.fields.reduce((total, item) => {
                return total.concat(item.fields);
            }, []);
        }

        const fields = options.fields
            ? options.fields
                .filter(item => item.preInsert)
                .map(item => {
                    let copyItem = this.deepExtend(item);
                    if (options.disableNotEmptyValidate !== true) {
                        if (!copyItem.validators) {
                            copyItem.validators = [];
                        }
                        if (!copyItem.validators.includes('notEmpty')) {
                            copyItem.validators.push('notEmpty');
                        }
                    }
                    if (options.displayReadonly !== false && copyItem.readonly === true) {
                        delete copyItem.readonly;
                    }
                    copyItem.colspan = 1;
                    return copyItem;
                })
            : null;

        const insert = () => {
            modal && modal.window.showMask();
            const data = ['', [this.extend(form ? form.getData() : null, options.param)]];
            let bizId = null;

            //没有预新增字段直接新增
            this.postText(
                options.url,
                this.getJsonWrapper(form ? { t: getFieldInfoByData(form.getData()) } : null, data),
            )
                .then(id => {
                    bizId = id;
                    if (!form) {
                        return this.getDeferred().resolve();
                    }
                    return form.uploadSingleFile(options.dbTable, id);
                })
                .done(() => {
                    modal && modal.close();
                    modal && modal.window.closeMask();
                    def.resolve(bizId);
                })
                .fail(() => {
                    modal && modal.window.closeMask();
                });
        };

        const insertEmpty = () => {
            let bizId = null;
            const data = ['', [this.extend(null, options.param)]];

            //没有预新增字段直接新增
            this.postText(
                options.url,
                this.getJsonWrapper(null, data),
            )
                .then(id => {
                    bizId = id;
                    return this.getDeferred().resolve();
                })
                .done(() => {
                    def.resolve(bizId);
                })
                .fail(() => {
                });
        };

        //没有预新增字段，直接插入数据
        if (this.isEmpty(fields)) {
            insertEmpty();
            return def;
        }

        const highHeightTypes = ['textarea', 'image', 'checkbox'];
        const highTypeFields = fields.filter(item => {
            return highHeightTypes.indexOf(item.type) > -1;
        });

        /**
         * 118 = 108 + 10
         * 108:modal 头部和底部
         * 10 ：form  padding-top
         * 42: input 高30  + margin-bottom 12
         * 8: 多文本比单文本多出的高度
         */
        // const modalHeight = fields.length * 50 * 1.5 + highTypeFields.length * 8 + 118;
        const modalHeight = 42 * fields.length + 8 * highTypeFields.length + 118

        const modal = this.create('modal', {
            title: options.modalTitle,
            titleStyle: options.modalStyle,
            width: options.width || 400,
            height: options.height || modalHeight,
        });

        const layout = this.create('layout', {
            renderTo: modal.window.$dom,
            center: {
                items: [
                    {
                        type: 'btnToolbar',
                        items: [
                            {
                                type: 'button',
                                text: Gikam.propI18N('GIKAM.BUTTON.CONFIRM'),
                                class: 'blue',
                                icon: 'save',
                                color: 'white',
                                onClick() {
                                    if (form.validate()) {
                                        insert();
                                    }
                                },
                            },
                            {
                                type: 'button',
                                text: Gikam.propI18N('GIKAM.BUTTON.CANCEL'),
                                icon: 'back',
                                onClick() {
                                    modal.close();
                                },
                            },
                        ],
                    },
                ],
            },
        });

        const form = this.create('form', {
            renderTo: layout.options.center.$dom,
            columns: options.columns || 1,
            titleWidth: options.titleWidth || 110,
            fields: fields,
            autoSave: false,
            // layout: 'vertical',
        });

        if (options.onFormRendered) {
            options.onFormRendered.apply(form);
        }

        const getFieldInfoByData = data => {
            const fieldInfo = {};
            form.options.fields.forEach(fieldOptions => {
                if (
                    this.isNotEmpty(data[fieldOptions.field], true) &&
                    ['select', 'simpleCheckbox'].indexOf(fieldOptions.type) > -1
                ) {
                    const options = {
                        type: fieldOptions.type === 'simpleCheckbox' ? 'checkbox' : fieldOptions.type || 'text',
                    };
                    if (fieldOptions.type === 'select') {
                        options.items = fieldOptions.items;
                    }
                    fieldInfo[fieldOptions.field] = options;
                }
            });
            return fieldInfo;
        };

        return def;
    },

    // 低代码
    getLcdpFormatterGridColumns: function (columns, gridId, isAddType) {
        let index = 5;
        if (isAddType === 'true') {
            index = index + 1;
        }
        columns.splice(index, 0, {
            field: 'operation',
            title: 'T_LIMS_REPORT_TEMPLATE.OPTION',
            contentAlign: 'center',
            width: 300,
            sort: false,
            formatter: function (index, value, row) {
                return Gikam.printf('<a href="javascript:;" onclick="Gikam.openFile(\'{id}\', false)">{name}</a>&nbsp;&nbsp;<a href="javascript:;" onclick="downloadFileById(\'{url}\',\'{gridId}\', false)">{download}</a>&nbsp;&nbsp;<a href="javascript:;" onClick="createFileOperationLogModal(\'{id2}\', true)">{option}</a>', {
                    id: row.id,
                    name: Gikam.propI18N('T_CORE_FILE.OPERATE.PREVIEW'),
                    url: IFM_CONTEXT + row.downloadUrl,
                    gridId : gridId,
                    download: Gikam.propI18N('T_CORE_FILE.OPERATE.DOWNLOAD'),
                    id2: row.id,
                    option: Gikam.propI18N('T_CORE_FILE.OPERATE.OPERATION.RECORD')
                });
            }
        });
        return columns.slice(0, index + 1);
    },

    // 订单编辑页 / 详情弹窗框
    loadBatchDetailPageV12 : function(batchId, readonly) {
        Gikam.getJson(Gikam.printf(IFM_CONTEXT + '/secure/basemodule/business/batchs/detail/page/{id}', {
            id: batchId
        })).done(function (r) {
            var pageUrl = IFM_CONTEXT + '/secure/basemodule/business/batchs/page/detail';
            // if(Gikam.isNotEmpty(r.ext$.detailpage)) {
            //     pageUrl = pageUrl + '-' + r.ext$.detailpage;
            // }
            if(readonly) {
                Gikam.create('modal', {
                    height: '90%',
                    width: '90%',
                    title: 'BASELINE.BUSINESS.BATCH.MODAL.DETAIL',
                    url: pageUrl + Gikam.param({
                        id : batchId,
                        topPage: '1',
                        readonly : '1'
                    }),
                })
            } else {
                workspace.window.load(pageUrl + Gikam.param({
                    id : batchId,
                    selected : r.selected,
                }));
            }

        })

    },

    fpRightFun : function(holeData){
        if (Gikam.isNotEmpty(holeData.sampleId)){
            Gikam.alert('孔已被占用',1);
            return;
        }
        let sampleGrid = Gikam.getComp('lims-storage-location-board2-sample-list-grid');
        let row = sampleGrid.getActivedRow();
        if (Gikam.isEmpty(row)){
            Gikam.toast('未选中样本',1);
            return;
        }
        if (Gikam.isNotEmpty(row.boardHoleId)){
            Gikam.toast('该样本已分配位置',1);
            return;
        }
        workspace.window.showMask();
        Gikam.postText(limsLocationBoard.baseUrl + '/ksh-assign-location',Gikam.getJsonWrapper({sampleId : row.id},[null,[holeData]])).done(function () {
            sampleGrid.refreshRowById(row.id);
            const  iframeDom=document.querySelector("#ksh-storage-location-board2-iframe >iframe");
            iframeDom.contentWindow.postMessage({
                type : 1
            }, "*");
        }).always(function () {
            workspace.window.closeMask();
        });
    },

    viewAuditNew : function(tableName, id) {
        Gikam.create('modal', {
            height: '60%',
            width: '60%',
            title: 'GIKAM.AT.TITLE.VIEW',
            url: IFM_CONTEXT + '/secure/core/module/sys/audit/audit-logs/page/record-detail' + Gikam.param({
                tableName: tableName,
                id : id,
            }),
        })
    },
});